package osb.map.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import com.map6.Map6Activity;
import com.map6.TestActivity;

import android.app.AlertDialog;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * socket线程
 * @author Administrator
 *
 */

public class BusSocket implements Runnable
{
	public static BusSocket Public_Static_BusSocket;
	private static final int PORT = 7788; 
	private Socket socket;
	private ObjectInputStream objIn;
	private ObjectOutputStream objOut;
	
//	private String severIP = "192.168.1.116"; 
	private String severIP = "61.146.153.230";
	
	public static boolean flag = false;
	
	 /**
	  * open socket
	  */
	public void BuildClientSocket()
	{
		Public_Static_BusSocket = this;
		try
		{
			socket = new Socket(severIP, PORT);
			objIn = new ObjectInputStream(socket.getInputStream());
			objOut = new ObjectOutputStream(socket.getOutputStream());
			flag = true;
		} 
		catch (Exception e)
		{
			mHandler1.sendEmptyMessage(1);
			return;
		}
	}

	/**
	 * close socket
	 */
	public void exitServer()
	{
		try
		{
			DataPackage data = new DataPackage(msgType.Exit);
			objOut.writeObject(data);
			objOut.close();
			objIn.close();
			socket.close();
		} 
		catch (Exception e)
		{
			Log.v("中断连接失败", "网络连接错误");
		}
		flag = false;
		socket = null;
		objOut = null;
		objIn = null;
	}
	
	/**
	 * send
	 * @param data
	 */
	public void sendMsg(DataPackage data)
	{
		if (flag == false)
		{
			Log.v("发送数据包出错，错误：网络连接失败","网络错误");
			System.out.println("发送数据包出错，错误：网络连接失败----网络错误"+'\n'); 
			return;
		}
		try
		{	
			objOut.writeObject(data);
		} 
		catch (Exception e)
		{
			Log.v("发送数据包出错，错误：数据包发送失败","网络错误");
			System.out.println("发送数据包出错，错误：数据包发送失败----网络错误"+'\n');
		}
	}

	/**
	 * thread=new Thread(new ClientSocket()); 
	 * thread.start();
	 */
	private DataPackage savaData;
	public void run()
	{
		boolean IsPostBack = true; 
		int Connect_error_count = 0; 
		while (!flag) 
		{
			BuildClientSocket();
			if (!flag) 
			{
				Connect_error_count++;
				if (IsPostBack) 
				{
					Log.v("第一次连接而且连接失败", "网络连接错误");
					IsPostBack = false;
				}
				if (Connect_error_count>2)  
				{
					mHandler1.sendEmptyMessage(1);	
					return;
				}
				Log.v("第" + Connect_error_count + "次尝试连接失败", "网络连接错误");
			}
		}
		
		//连接成功
		mHandler1.sendEmptyMessage(0);

		// 注册busID
		if(Map6Activity.staticBusID != -1)
		{
			DataPackage data = new DataPackage( msgType.Bus_Reg);
			data.dataGPS = new DataGPS(Map6Activity.staticBusID);
			sendMsg(data);
		}
	
		// 监听
		while (true)
		{
			try
			{
				DataPackage data = (DataPackage) objIn.readObject();
				// 支付请求
				if (data.type == msgType.Pay_User)     
				{
					savaData=data;
					data.dataPay.getXiaolvid();
					mHandler1.sendEmptyMessage(2);	
				} 
				// 重复BUSID
				if (data.type == msgType.RepeatBusID)     
				{
					mHandler1.sendEmptyMessage(3);	
					return;
				} 
			}
			// 连接中断
			catch (IOException e)
			{
				mHandler1.sendEmptyMessage(4);	
				return;
				
//				e.printStackTrace();
			} 
			catch (ClassNotFoundException e)
			{
				e.printStackTrace();
			}
		}
	}


	Handler mHandler1 = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			// 连接成功
			case 0:    
				Map6Activity.btn_connect.setText("已连接");
				break;
			// 连接失败
			case 1:    
				new AlertDialog.Builder(Map6Activity.Public_Static_Map)
                .setMessage("服务器连接失败")
                .setPositiveButton("确定", null)
                .show();
				Map6Activity.thread = null;
				Map6Activity.et_busID.setEnabled(true);
				Map6Activity.btn_connect.setEnabled(true);
				Map6Activity.btn_connect.setText("连接");
				break;
			// 支付请求	
			case 2:     
				Map6Activity.Public_Static_Map.addPayUser(savaData);
				break;
			// 重复busID
			case 3:     
				new AlertDialog.Builder(Map6Activity.Public_Static_Map)
                .setMessage("BusID冲突，连接中断，请重新连接")
                .setPositiveButton("确定", null)
                .show();
				exitServer();
				Map6Activity.thread = null;
				Map6Activity.et_busID.setEnabled(true);
				Map6Activity.btn_connect.setEnabled(true);
				Map6Activity.btn_connect.setText("连接");
				break;
			// 服务器中断连接
			case 4: 			
				new AlertDialog.Builder(Map6Activity.Public_Static_Map)
                .setMessage("服务器中断连接，请稍候重新连接")
                .setPositiveButton("确定", null)
                .show();
				exitServer();
				Map6Activity.thread = null;
				Map6Activity.et_busID.setEnabled(true);
				Map6Activity.btn_connect.setEnabled(true);
				Map6Activity.btn_connect.setText("连接");
				break;
			default:break;
			}
		}
	};
}
